/*
 * Description: 登录状态中心
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Dongxu.Ni
 * Date: 2020/3/10 15:19
 */
import { PATH_SEPARATOR } from '../../const/route-path'
import router, { lastRequiredRoutes, privateRoutes, resetRouter } from '../../router'
import { removeAuthToken } from '../../utils/browser'
import { LOGIN_PATH } from '../../const/route-path'

// 按照会话岗位的菜单列表，比对全部私有路由，生成全新的路由信息
function initDynamicRoute(menuList, routes, parentRoutePath) {
  const retRoutes = []
  if (menuList && menuList.length > 0) {
    for (const route of routes) {
      let routeFullPath = parentRoutePath + PATH_SEPARATOR + route.path
      routeFullPath = routeFullPath.replace('//', '/')
      const routeChildren = route.children
      const newRoute = {
        path: route.path,
        name: route.name,
        component: route.component,
        meta: {
          routeFullPath: routeFullPath,
          buttons: []
        }
      }
      // 1 查看自身路由有无对应菜单
      const mapMenu = menuList.find(m => !m.isCatalog && m.menuId === routeFullPath)
      // 1.1 有，则解析
      if (mapMenu) {
        if (mapMenu.menuFuncList && mapMenu.menuFuncList.length > 0) {
          for (const menuFunc of mapMenu.menuFuncList) {
            newRoute.meta.buttons.push(menuFunc.bindButton)
          }
        }
        newRoute.meta.order = mapMenu.order
      }
      // 2 查看子路由有无对应菜单
      let newChildRoutes
      if (routeChildren && routeChildren.length > 0) {
        newChildRoutes = initDynamicRoute(menuList, routeChildren, routeFullPath)
        if (newChildRoutes && newChildRoutes.length > 0) {
          // 排序
          newChildRoutes.sort((a, b) => {
            return a.meta.order - b.meta.order
          })
          newRoute.children = newChildRoutes
          newRoute.redirect = newChildRoutes[0].meta.routeFullPath
        }
      }
      if (mapMenu || newChildRoutes) {
        retRoutes.push(newRoute)
      }
    }
  }
  return retRoutes
}
const state = {
  // 登录初始化状态，默认没有初始化过，调用initAfterLogin置为true
  loginInitialized: false,
  // 当前会话动态路由集合
  sessionRoutes: []
}

const getters = {
  getLoginInitialized: state => state.loginInitialized
}

const mutations = {
  SET_LOGIN_INITIALIZED: state => {
    state.loginInitialized = true
  },
  SET_SESSION_ROUTES: (state, sessionRoutes) => {
    state.sessionRoutes = sessionRoutes
  },
  REMOVE_LOGIN_INITIALIZED: state => {
    state.loginInitialized = false
  }
}

const actions = {
  /* 在登录之后完成一系列必须的初始化*/
  async initAfterLogin({ commit, dispatch, rootState }) {
    try {
      // 初始化当前用户基本信息
      await dispatch('user/initSessionUser', null, { root: true })
      // 初始化当前用户岗位信息
      await dispatch('post/initSessionPost', null, { root: true })
      // 初始化当前岗位菜单信息
      await dispatch('menu/initSessionPostMenuList', null, { root: true })
      // 动态初始化路由信息
      const sessionPostMenuList = rootState.menu.sessionPostMenuList
      const dynamicRoute = initDynamicRoute(sessionPostMenuList, privateRoutes, '')
      commit('SET_SESSION_ROUTES', dynamicRoute)
      router.addRoutes(dynamicRoute)
      router.addRoutes(lastRequiredRoutes)
      commit('SET_LOGIN_INITIALIZED')
      // 初始化全局字典信息
      await dispatch('dict/initDictCollects', null, { root: true })
      // 初始化全局用户简要信息
      await dispatch('user/initUserSimpleCollects', null, { root: true })
      // 初始化全局岗位简要信息
      await dispatch('post/initPostSimpleCollects', null, { root: true })
      // 初始化全局菜单信息
      await dispatch('menu/initMenuCollects', null, { root: true })
      // 初始化全局接口信息
      await dispatch('api/initApiCollects', null, { root: true })
      // 初始化下级岗位信息
      await dispatch('post/initSubPostList', null, { root: true })
    } catch (error) {
      console.log(error)
      return Promise.reject(error)
    }
  },
  // 登出  去除一系列状态
  logout({ commit }, oldPath) {
    removeAuthToken()
    // 重置路由，否则会发生路由add重复
    resetRouter()
    commit('REMOVE_LOGIN_INITIALIZED')
    const replacePath = LOGIN_PATH + (oldPath ? '?redirect=' + oldPath : '')
    router.replace({ path: replacePath }).catch(err => console.log(err, 'store/login'))
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
